<?php

class Cms_Model_Users extends Zend_Db_Table_Abstract
{
    protected $_name = 'users';
    protected $_primary = 'userId';
    protected $_rowClass = 'Cms_Model_User';
    protected $_dependentTables = array('Application_Model_Iscriziones');
    
    /**
     * Create a new User
     *
     * @param string $nome  Nome
     * @param string $email Email - usata per il Login
     * @param string $role Ruolo
     * @param string $tel Telefono
     * @param string $password Password
     * @return Cms_Model_User
     * @throws Zend_Exception 
     */
    public function createUser($nome, $email, $password, $role = 'user', $tel = NULL)
    {
        try{
            // Create a new row
            $rowUser = $this->createRow();
            if($rowUser) {
                // Update the row values
                $rowUser->userNome = $nome;
                $rowUser->userEmail = $email;
                $rowUser->userRole = $role;
                $rowUser->userPassword = md5($password);
                $rowUser->userTel = $tel;
                $rowUser->save();
                // Return the new user
                return $rowUser;
            }
        } catch (Zend_Db_Statement_Exception $e) {
            if ($e->getPrevious()) {
                if ($e->getCode() == 23000) {
                    echo "<p class=\"alert\">La password o la email sono già presenti nel sistema</p>";
                }
            } else {
                throw new Zend_Exception("Non è possibile creare un nuovo utente");
            }
        }
    }
    
    public function getUserById($id)
    {
            $user = $this->find($id)->current();
            if ($user) {
                return $user;
            } else {
                throw new Zend_Exception("L'utente cercato non esiste");
            }
    }

    /**
     * Returns all users
     * 
     * @return Zend_Db_Table_Rowset
     */
    static function getUsers()
    {
        $userModel = new self();
        $select = $userModel->select();
        $select->order(array('userId'));
        return $userModel->fetchAll($select);
    }
    
    /** 
     * Update exising user
     * 
     * @param int $id
     * @param string $nome
     * @param string $email
     * @param string $role
     * @param string $tel
     * @return Cms_Model_User
     * @throws Zend_Exception
     */
    public function updateUser($id, $nome, $email, $role, $tel, $tessera)
    {
        // Fetch the user row
        $rowUser = $this->getUserById($id);
        
        if($rowUser) {
            // Update the row values
            $rowUser->userNome = $nome;
            $rowUser->userEmail = $email;
            $rowUser->userRole = $role;
            $rowUser->userTel = $tel;
            $rowUser->userTessera = $tessera;
            $rowUser->save();
            // Return the updated user
            return $rowUser;
        } else {
            throw new Zend_Exception("Utente non presente");
        }
    }
    
    public function updateTelUser($id, $tel)
    {
        // Fetch the user row
        $rowUser = $this->getUserById($id);
        
        if($rowUser) {
            // Update the row values
            $rowUser->userTel = $tel;
            $rowUser->save();
            // Return the updated user
            return $rowUser;
        } else {
            throw new Zend_Exception("Utente non presente");
        }
    }
    
    public function updateTesseraUser($id, $tessera)
    {
        // Fetch the user row
        $rowUser = $this->getUserById($id);
        
        if($rowUser) {
            // Update the row values
            $rowUser->userTessera = $tessera;
            $rowUser->save();
            // Return the updated user
            return $rowUser;
        } else {
            throw new Zend_Exception("Utente non presente");
        }
    }
    
    public function updatePassword($id, $password)
    {
        // Fetch the user row
        $rowUser = $this->getUserById($id);
        
        if($rowUser) {
            // Update pasword
            $rowUser->userPassword = md5($password);
            $rowUser->save();
            return $rowUser;
        } else {
            throw new Zend_Exception("Aggiornamento della password fallito. Utente non presente");
        }
    }
    
    public function deleteUser($id)
    {
        // Fetch the user row
        $rowUser = $this->getUserById($id);
        
        if ($rowUser) {
            $rowUser->delete();
        } else {
            throw new Zend_Exception("Non posso cancellare l'utente. Utente non trovato");
        }
    }
    
    /**
     * Create array o names for select elements of UserFilterForm 
     * 
     * @return array of names
     */
    public function createArrayNames()
    {
        $users = self::getUsers();
        
        $arrayOfNames = array();
        foreach ($users as $user) {
            $arrayOfNames["$user->userId"] = $user->userNome;
        }
        
        return $arrayOfNames;
    }
}

